# coding=UTF-8

import sys,os
from google.appengine.api import users
from google.appengine.ext.webapp import template
import datetime
from google.appengine.ext import db
from model.tag import Tag
from model.greeting import Greeting

def topTags():
  tags = db.GqlQuery("SELECT * "
                            "FROM Tag "
                            "ORDER BY count DESC limit 20")
  return tags

def months():
  now = datetime.datetime.now()
  days = []
  for i in range(0,23):
    month=now.month-i
    year=now.year
    while month<1:
      month+=12
      year-=1
    day = datetime.datetime(year,month,1)
    days.append(day)
  return days

def topGreetings():
  greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "ORDER BY date DESC limit 10")
  return greetings

def renderSimple(templatePath,model,requestHandler):
  path = os.path.join(os.path.dirname(__file__), templatePath)
  requestHandler.response.out.write(template.render(path, model))

def render(templatePath,model,requestHandler):
  path = os.path.join(os.path.dirname(__file__), templatePath)
  model['context']=Context(requestHandler.request)
  model['months']=months()
  model['tags']=topTags()
  model['greetings']=topGreetings()
  requestHandler.response.out.write(template.render(path, model))
  
class PageInfo:
  pageSize=10
  recordCount=0
  pageNo=1
  def __init__(self, recordCount, pageNoStr,pageSize):
    self.recordCount = recordCount
    if (pageNoStr.isdigit()):
      self.pageNo=int(pageNoStr)
    if (pageSize):
      self.pageSize=pageSize
    self.pageCount=int(recordCount//self.pageSize)+1
    self.hasPrevPage=(self.pageNo>1)
    self.hasNextPage=(self.pageCount>self.pageNo)
    self.prevPage=self.pageNo-1
    self.nextPage=self.pageNo+1
    self.pageCountRange=range(1,self.pageCount+1)
  def startOffset(self):
    return  self.pageSize*(self.pageNo-1)
    
class Context:
  def __init__(self, request):
    self.user=users.get_current_user()
    self.request=request
  def loginUrl(self):
    if self.user:
      url = users.create_logout_url(self.request.uri)
    else:
      url = users.create_login_url(self.request.uri)
    return url
    
  def isAdmin(self):
    return users.is_current_user_admin()
  def nickname(self):
    return self.user.nickname();
  def loginText(self):
    if self.user:
      url_linktext = '退出登录'
    else:
      url_linktext = '登录'
    return url_linktext
  def welcomeText(self):
    if self.user:
      welcome_text = '欢迎你' + self.user.nickname()
    else:
      welcome_text = '欢迎你'
    return welcome_text
